package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.NursingRecordDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 护理记录
 */

@RequestMapping("NursingRecord")
@RestController
public class NursingRecordController extends BaseController {

    @Autowired
    @Qualifier("NursingRecordServiceImplOne")
    private NursingRecordService nursingRecordService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("NurseAideServiceImplOne")
    private NurseAideService nurseAideService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("NursingItemServiceImplOne")
    private NursingItemService nursingItemService;

    @Autowired
    @Qualifier("NurseServiceImplOne")
    private NurseService nurseService;


    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;

    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;




    //机构后台
    @RequestMapping(value = "InsPage", method = RequestMethod.POST)
    public MyResult InsPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck =checkSignAdmInterface(timeStr,sign,staffCode,"/NursingRecord/Page");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            PageInfo<NursingRecord> pageInfoNursingRecord = nursingRecordService.getPageList(pageIndex, pageSize, institutionCode);

            return success(pageInfoNursingRecord);

        } catch (Exception e) {
            insertError("/NursingRecord/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构App
    @RequestMapping(value = "InsPageApp", method = RequestMethod.POST)
    public MyResult InsPageApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck =checkSignFrontInterface(timeStr,sign,"/NursingRecord/InsPageApp");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            Institution institution = institutionService.getByUserCode(userCode);
            String institutionCode = institution.getInstitutionCode();

            PageInfo<NursingRecord> pageInfo = nursingRecordService.getPageList(pageIndex, pageSize, institutionCode);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/InsPageApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //服务中
    @RequestMapping(value = "InsPageDongApp", method = RequestMethod.POST)
    public MyResult InsPageDongApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck =checkSignFrontInterface(timeStr,sign,"/NursingRecord/InsPageDongApp");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            Institution institution = institutionService.getByUserCode(userCode);
            String institutionCode = institution.getInstitutionCode();

            PageInfo<NursingRecord> pageInfo = nursingRecordService.pageByInstitutionCode(pageIndex, pageSize, institutionCode,1);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/InsPageDongApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //gov
    @RequestMapping(value = "GovPage", method = RequestMethod.POST)
    public MyResult GovPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck =checkSignAdmInterface(timeStr,sign,staffCode,"/NursingRecord/Page");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<NursingRecord> pageInfoNursingRecord = nursingRecordService.pageByGovCode(pageIndex, pageSize, staff.getGovernmentCode());

            return success(pageInfoNursingRecord);
        } catch (Exception e) {
            insertError("/NursingRecord/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //gov服务中
    @RequestMapping(value = "GovListDong", method = RequestMethod.POST)
    public MyResult GovListDong(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String govCode = jsonObject.getString("govCode");

            PreCheck preCheck =checkSignFrontInterface(timeStr,sign,"/NursingRecord/InsPageDongApp");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            List<NursingRecord> list = nursingRecordService.listByGovCodeStatus(govCode,1);

            List<NursingRecordDTO> listDTO = new ArrayList<>();
            for(NursingRecord nursingRecord:list){
                NursingRecordDTO nursingRecordDTO = mapper.map(nursingRecord,NursingRecordDTO.class);
                String recordType = nursingRecordDTO.getRecordType();
                User user = null;
                if(recordType.equals("mediciner")){
                    Mediciner mediciner = medicinerService.getByMedicinerCode(nursingRecord.getMedicinerCode());
                    user = userService.getByUserCode(mediciner.getUserCode());
                }
                if(recordType.equals("nurse")){
                    Nurse nurse = nurseService.getByNurseCode(nursingRecord.getNurseCode());
                    user = userService.getByUserCode(nurse.getUserCode());
                }
                if(recordType.equals("nurseAide")){
                    NurseAide nurseAide = nurseAideService.getByNurseAideCode(nursingRecord.getNurseAideCode());
                    user = userService.getByUserCode(nurseAide.getUserCode());
                }
                nursingRecordDTO.setUser(user);
                listDTO.add(nursingRecordDTO);
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("list",listDTO);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/InsPageDongApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //serve
    @RequestMapping(value = "ServePageApp", method = RequestMethod.POST)
    public MyResult ServePageApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck =checkSignFrontInterface(timeStr,sign,"/NursingRecord/ServePageApp");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);

            int userType = user.getUserType();
            PageInfo<NursingRecord> pageInfo = null;
            if(userType==7){
                Mediciner mediciner = medicinerService.getByUserCode(userCode);
                pageInfo = nursingRecordService.pageByMedicinerCode(pageIndex,pageSize,mediciner.getMedicinerCode(),2);
            }else if(userType==8){
                Nurse nurse = nurseService.getByUserCode(userCode);
                pageInfo = nursingRecordService.pageByNurseCode(pageIndex,pageSize,nurse.getNurseCode(),2);
            }else if(userType==9){
                NurseAide nurseAide = nurseAideService.getByUserCode(userCode);
                pageInfo = nursingRecordService.pageByNurseAideCode(pageIndex,pageSize,nurseAide.getNurseAideCode(),2);
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/NursingRecord/ServePageApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //服务人员查看正在服务的护理
    @RequestMapping(value = "ServeListDoing", method = RequestMethod.POST)
    public MyResult ServeListDoing(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/GetNursingList");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            int userType = user.getUserType();

            List<NursingRecord> list = null;
            if(userType==7){
                Mediciner mediciner = medicinerService.getByUserCode(userCode);
                list = nursingRecordService.listByMedicinerCode(mediciner.getMedicinerCode(),1);
            }else if(userType==8){
                Nurse nurse = nurseService.getByUserCode(userCode);
                list = nursingRecordService.listByNurseCode(nurse.getNurseCode(),1);
            }else if(userType==9){
                NurseAide nurseAide = nurseAideService.getByUserCode(userCode);
                list = nursingRecordService.listByNurseAideCode(nurseAide.getNurseAideCode(),1);
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("list",list);

            return success(list);
        } catch (Exception e) {
            insertError("/NursingRecord/ServeListDoing", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //患者查看护理记录
    @RequestMapping(value = "ElderlyPageApp", method = RequestMethod.POST)
    public MyResult ElderlyPageApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/ElderlyPageApp");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByUserCode(userCode);

            PageInfo<NursingRecord> pageInfo = nursingRecordService.getPageListByElderlyCode(pageIndex,pageSize,elderly.getElderlyCode());

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/ElderlyPageApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //月服务总数
    @RequestMapping(value = "ElderlyMonthCount", method = RequestMethod.POST)
    public MyResult ElderlyMonthCount(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/ElderlyMonthCount");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByUserCode(userCode);

            String dd = sdfYMD.format(new Date());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(sdfYMD.parse(dd));
            Date beiginTime = calendar.getTime();
            calendar.add(calendar.MONTH, 1);
            Date endTime = calendar.getTime();

            System.out.println(sdfYMD.format(beiginTime)+"--"+sdfYMD.format(endTime));

            List<NursingRecord> list = nursingRecordService.listByElderlyCodeTime(elderly.getElderlyCode(),
                    beiginTime,endTime);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("count",list.size());

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/ElderlyMonthCount", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //记录信息
    @RequestMapping(value = "Info", method = RequestMethod.POST)
    public MyResult Info(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String nursingRecordCode = jsonObject.getString("nursingRecordCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/Info");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            NursingRecord nursingRecord = nursingRecordService.getByNursingRecordCode(nursingRecordCode);
            Elderly elderly = elderlyService.getByElderlyCode(nursingRecord.getElderlyCode());

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("nursingRecord",nursingRecord);
            jsonObject1.put("elderlyUserCode",elderly.getUserCode());
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/Info", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //添加病开始护理
    @RequestMapping(value = "Start", method = RequestMethod.POST)
    public MyResult Start(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            String elderlyCode = jsonObject.getString("elderlyCode");
            String nursingItemCode = jsonObject.getString("nursingItemCode");

            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            String address = jsonObject.getString("address");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/Start");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            NursingRecord nursingRecord = new NursingRecord();

            User user = userService.getByUserCode(userCode);
            int userType = user.getUserType();
            if(userType == 7){
                Mediciner mediciner = medicinerService.getByUserCode(userCode);
                nursingRecord.setMedicinerCode(mediciner.getMedicinerCode());
                nursingRecord.setMedicinerName(user.getName());
                nursingRecord.setRecordType("mediciner");
            }else if(userType ==8){
                Nurse nurse = nurseService.getByUserCode(userCode);
                nursingRecord.setNurseCode(nurse.getNurseCode());
                nursingRecord.setNurseName(user.getName());
                nursingRecord.setRecordType("nurse");
            }else if(userType==9){
                NurseAide nurseAide = nurseAideService.getByUserCode(userCode);
                nursingRecord.setNurseAideCode(nurseAide.getNurseAideCode());
                nursingRecord.setNurseAideName(user.getName());
                nursingRecord.setRecordType("nurseAide");
            }

            String institutionCode = user.getInstitutionCode();

            Elderly elderly=elderlyService.getByElderlyCode(elderlyCode);
            NursingItem nursingItem = nursingItemService.getByNursingItemCode(nursingItemCode);

            nursingRecord.setNursingRecordCode(UUID.randomUUID().toString());
            nursingRecord.setElderlyCode(elderlyCode);
            nursingRecord.setElderlyName(elderly.getName());
            nursingRecord.setNursingItemCode(nursingItemCode);
            nursingRecord.setNursingItemName(nursingItem.getName());
            nursingRecord.setCreateTime(new Date());
            nursingRecord.setInstitutionCode(institutionCode);
            nursingRecord.setStatus(1);
            nursingRecordService.insert(nursingRecord);

            nursingRecord.setStartTime(new Date());
            nursingRecord.setLat(lat);
            nursingRecord.setLon(lon);
            nursingRecord.setAddress(address);
            nursingRecordService.update(nursingRecord);

            //make plan clock in time
            WriteSpanTime(nursingRecord.getNursingRecordCode(),nursingItemCode);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/NursingRecord/Start", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //结束护理
    @RequestMapping(value = "End", method = RequestMethod.POST)
    public MyResult End(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String nursingRecordCode = jsonObject.getString("nursingRecordCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr,sign,"/NursingRecord/End");
            if(preCheck.getError() == 1){
                return failed(preCheck.getMessage());
            }

            NursingRecord nursingRecord = nursingRecordService.getByNursingRecordCode(nursingRecordCode);

            nursingRecord.setEndTime(new Date());
            nursingRecord.setStatus(2);
            nursingRecordService.update(nursingRecord);


            Object object = new Object[]{};
            return success(object);
        } catch (Exception e) {
            insertError("/NursingRecord/End", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //写随机打卡时间文件
    private void WriteSpanTime(String nursingRecordCode,String nursingItemCode){

        NursingItem nursingItem = nursingItemService.getByNursingItemCode(nursingItemCode);

        Date startTime = new Date();

        int duration = nursingItem.getDuration();
        //duration = 120;

        //1~10之间
        int count = (int)(Math.random()*10)+1;
        System.out.println("count:"+count);

        int[] arr = new int[count];
        for(int i=0;i<count;i++){
            int k = (int)(Math.random()*10)+1;
            arr[i]=k;
            System.out.println("arr:"+k);
        }


        String nursingPath = push+File.separator+"nursing";
        String nurisngRecordCodePath = nursingPath+File.separator+nursingRecordCode;
        String nurisngWillPush = nursingPath+File.separator+"willPush";
        File file = new File(nurisngRecordCodePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file2 = new File(nurisngWillPush);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        //获取最小的时间段
        int minTime = 10;
        for(int i=0;i<arr.length;i++){
            if(arr[i]<minTime){
                minTime = arr[i];
            }
        }

        for(int i=0;i<arr.length;i++){

            //随机时间段
            int spanTime = (int)(arr[i]*0.1*duration);
            System.out.println("spanTime:"+spanTime);

            //时间段的打卡时间
            long clockInTime = startTime.getTime()+spanTime*60*1000;
            String fileName = clockInTime+".txt";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("time",format.format(new Date(clockInTime)));
            jsonObject1.put("nursingRecordCode",nursingRecordCode);

            if(arr[i] == minTime){
                //最小的写入推送中
                String filePathTxt2 = nurisngWillPush+File.separator+fileName;
                saveAsFileWriter(filePathTxt2,jsonObject1.toJSONString());
            }else{
                //等待推送
                String filePathTxt = nurisngRecordCodePath+File.separator+fileName;
                saveAsFileWriter(filePathTxt,jsonObject1.toJSONString());
            }


        }


    }


}
